package com.cy.mall.web.comm;

import com.cy.mall.model.PageBean;
import com.cy.mall.model.Result;
import com.cy.mall.model.doc.WechatMessageTemplateLog;
import com.cy.mall.model.domain.customer.CustomerWechat;
import com.cy.mall.model.enums.wechat.WechatSopce;
import com.cy.mall.service.wechat.WechatService;
import com.cy.mall.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @Description 微信
 * @Author tanyilin
 * @Date 2019/3/14 18:08
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
@Api(tags = "微信相关api")
public class WechatController extends BaseController {

    @Autowired
    private WechatService wechatService;
    @Value("${app.home.page}")
    private String appHomePage;

    @ApiOperation("公众号验证token")
    @GetMapping("/verify/token")
    public String verifyToken(String echostr) {
        return echostr;
    }

    @ApiOperation("获取微信分享签名")
    @GetMapping("/share/signature")
    public Result<Map<String, String>> getShareSignature(String url) {
        //获取基础accessToken
        String token = wechatService.getBaseAccessToken();
        //基础accessToken 获取ticket
        String ticket = wechatService.getTicket(token);
        //获取微信分享签名
        Map<String, String> map = wechatService.getShareSignature(token, ticket, url);
        return ok("", map);
    }

    @ApiOperation("获取微信用户授权地址url")
    @GetMapping("/authorize/url")
    public Result<String> getAuthorizeUrl(WechatSopce wechatSopce) {
        Long customerId = this.getLoginCustomer().getCustomerId();
        String url = wechatService.getAuthorizeUrl(customerId, wechatSopce);
        return ok("", url);
    }

    @ApiOperation("绑定用户授权回调方法")
    @GetMapping("/bind/callback")
    public ModelAndView bindCallback(String code, String state) {

        log.info("绑定用户授权回调方法  ======== start");
        CustomerWechat customerWechat = wechatService.bindCallback(code, state);
        wechatService.bindCustomerWechat(customerWechat);
        log.info("绑定用户授权回调方法  ======== end");

        return new ModelAndView("redirect:".concat(appHomePage));
    }

    @ApiOperation("查询微信消息模板发送记录日志")
    @GetMapping("/get/message/send/logs")
    public PageBean<WechatMessageTemplateLog> getWechatMessageTemplateSendLog(String openId, int page, int limit) {

        PageBean<WechatMessageTemplateLog> pageBean = wechatService.getWechatMessageTemplateSendLog(openId, page, limit);
        return pageBean;
    }


}
